package com.lanyou.cook.upload.service.socket.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.MessageDigest;


public class FileCilent {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

			Socket client = null;
			try {
				client = new Socket("172.26.153.196", 8888);
				OutputStream os = client.getOutputStream();
				InputStream is = client.getInputStream();
				String filepath = "e:\\配置脚本.txt";
				/*String filepath = "d:\\apache-cxf-3.1.6-src.zip";*/
				
				File file = new File(filepath);
				String filename = file.getName();
				System.out.println("send's file name:" + filename);
				
				
				InputStream fis = new FileInputStream(file);
				
				InputStream fis1 = new FileInputStream(file);
				// 1、发送文件名
				MessageDigest md = MessageDigest.getInstance("MD5");
				// md.digest() 该函数返回值为存放哈希值结果的byte数组
				
				byte[] b = new byte[(int)file.length()];
				fis.read(b);
				byte[] md5b = md.digest(b);
				System.out.println("文件长度: " + file.length());
				StringBuilder ret=new StringBuilder(md5b.length<<1);
				for(int i=0;i<md5b.length;i++){
				  ret.append(Character.forDigit((md5b[i]>>4)&0xf,16));
				  ret.append(Character.forDigit(md5b[i]&0xf,16));
				}
				System.out.println(ret.toString());
				String str = filename + ":" + ret.toString() + ":" + file.length();
				os.write(str.getBytes("utf-8"));
				is.read();
				int length = 0;
				byte[] b2 = new byte[1024];
				while ((length = fis1.read(b2)) != -1) {
					// 2、把文件写入socket输出流
					//System.out.println(new String(b));
					System.out.println(length);
					os.write(b2, 0, length);
				}
//				fis1.read(b);
//				os.write(b);
				byte[] serverStr = new byte[256];
				
				is.read(serverStr);
				System.out.println("sdf" + new String(serverStr));
				String str1 = new String(serverStr);
				if(str1.trim().equals("ok")){
					is.close();
					os.close();
					fis.close();
					fis1.close();
				}
				System.out.println("send over");
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch(Exception e){
				e.printStackTrace();
			}finally {
			
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	

   

}
